import React, { Component } from 'react'
import { DatePicker,Switch } from 'antd';
import request from '../../util/request'

interface Iprops{
    history:any
}

interface Istate{
    title:string,
    desc:string,
    items:string[],
    endTime:string,
    isName:boolean,
    option:string,
    [propName:string]:any
}  
 

export default class Create extends Component<Iprops,Istate> {
    state = {
        title:'',
        desc:'',
        items:[],
        endTime:'',
        isName:false,
        option:''
    }
    render() {
        let {title,desc,items,endTime,isName,option} = this.state;
        return (
            <div>
                <div>
                    标题：<input type="text" value={title} name="title" onChange={this.changeVal}/><br></br>
                    描述:<input type="text" value={desc} name="desc" onChange={this.changeVal}></input>
                    选项:
                        <div>
                            {/* 选项 */}
                            <ul>
                                {items && items.map((item,index) => <li key={index}>{item} <button onClick={() => {this.del(index)}}>-</button></li>)}
                            </ul>
                            <div>
                                <input type="text" value={option} name="option" onChange={this.changeVal}/><button onClick={this.add}>添加选项</button>
                            </div>
                        </div>
                </div>
                <div>
                    截至日期：<DatePicker showTime onChange={this.onChange}/>
                    匿名投票：<Switch defaultChecked={false} onChange={ this.switch} />
                </div>
                <button onClick={this.create}>创建投票</button>    
            </div>
        )
    }
    //时间选择
    onChange = (value:any, dateString:string) => {
        console.log('Selected Time: ', value);
        console.log('Formatted Selected Time: ', dateString);
        this.setState({
            endTime:dateString
        })
    }

    //开关
    switch = (checked:boolean) => {
        console.log(checked);
    }

    changeVal = (e:any) => {
        this.setState({
            [e.target.name]:e.target.value
        })
    }

    //添加选项
    add = () => {
        let {option,items} = this.state;
        if(option){
            this.setState({
                items:[...items,option],
                option:''
            })
        }
    }

    //删除选项
    del = (index:number) => {
        let {items} = this.state;
        items.splice(index,1);
        this.setState({
            items
        })
    }

    //创建投票
    create = () => {
        let {title,desc,items,isName,endTime} = this.state;
        // title,desc,endTime,isName,items
        request.post('/api/createVote',{title,desc,items:items.join(','),isName:isName?1:2,endTime}).then(res => {
            console.log(res)
            if(res.data.code === 1){
                this.props.history.push('/main/home')
            }
        })
    }
}
